package com.fos.BluetoothStory.util;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;

import android.util.Log;
import android.util.SparseArray;

import com.fos.BluetoothStory.model.MusicBean;

/**
 * 存储设备端音乐数据
 * @author fanxing 创建于 Dec 23, 2015
 */
public class DeviceSongsCatch {
	
	private static SparseArray<HashSet<MusicBean>> deviceSongs = new SparseArray<HashSet<MusicBean>>();
	private static Comparator<MusicBean> comparator = new Comparator<MusicBean>() {
		
		@Override
		public int compare(MusicBean lhs, MusicBean rhs) {
			int lhs_id = lhs.id;
			int rhs_id = rhs.id;
			return lhs_id==rhs_id ? 0 : (lhs_id>rhs_id ? 1 : -1);
		}
	};
	
	public static boolean put(MusicBean bean){
		synchronized (deviceSongs) {
			int pid = bean.pid;//从1开始
			HashSet<MusicBean> musicArray = deviceSongs.get(pid);
			if(musicArray == null){
				musicArray = new HashSet<MusicBean>();
				deviceSongs.put(pid, musicArray);
			}
			if(musicArray.contains(bean))
				return false;
			Log.v("fan", "添加歌曲"+bean.title);
			musicArray.add(bean);
			return true;
		}
	}
	
	public static ArrayList<MusicBean> get(int pid){
		synchronized (deviceSongs) {
			HashSet<MusicBean> musicArray = deviceSongs.get(pid);
			if(musicArray == null){
				return new ArrayList<MusicBean>();
			}else{
				ArrayList<MusicBean> res = new ArrayList<>(musicArray);
				Collections.sort(res, comparator);
				return res;
			}
		}
	}
	
	public static void clear(int pid){
		HashSet<MusicBean> musicArray = deviceSongs.get(pid);
		if(musicArray == null){
			musicArray = new HashSet<MusicBean>();
		}else{
			musicArray.clear();
		}
		deviceSongs.put(pid, musicArray);
	}

	public static void clearAll(){
		deviceSongs.clear();
	}
}
